package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser>implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.检查参数
        if(StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //2.校验用户名和密码
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName,dto.getName());
        List<WmUser> list = list(wrapper);
        if(ObjectUtils.isEmpty(list)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        WmUser wmUser = list.get(0);
        String pw=dto.getPassword()+wmUser.getSalt();
        String pwd= DigestUtils.md5DigestAsHex(pw.getBytes());
        if(!wmUser.getPassword().equals(pwd)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"密码错误");
        }
        //生成token返回给前端
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        HashMap<Object, Object> map = new HashMap<>();
        wmUser.setSalt("");
        wmUser.setPassword("");
        map.put("token",token);
        map.put("wmUser",wmUser);
        return ResponseResult.okResult(map);
    }
}
